import { Component, OnInit, ElementRef, Renderer2, OnDestroy } from '@angular/core';
import { NavController, NavParams } from '@ionic/angular';
import { DataService } from '@services/data.service';
import { CacheService } from '@services/cache.service';
import { WashCartsService } from '@services/echarts/wash.echarts.service';
import { Observable } from 'rxjs';
import { DatePipe } from '@angular/common';


@Component({
  selector: 'wash-room',
  templateUrl: 'wash-room.html',
  styleUrls: ['wash-room.scss']
})

export class WashRoomPage implements OnInit {
  projectId;     // 项目id
  washTotal;     // 洗手间数据统计
  washRoom;      // 洗手间房间列表
  xItem;
  yItem;         // 已选择的洗手间
  itemShown;
  lastItem;
  lastData;
  options;       // 洗手间清扫统计折线图
  searchTime;

  constructor(
    public el: ElementRef,
    public renderer: Renderer2,
    public navCtrl: NavController,
    public dataService: DataService,
    public washCharts: WashCartsService,
    public cache: CacheService,
    public datePipe: DatePipe
  ) {
    const date = new Date();
    const toDay = this.formatDate(date, 'yyyy-MM-dd');
    const nextday = + date + 1000 * 60 * 60 * 24;
    const nextDay = this.formatDate(new Date(nextday), 'yyyy-MM-dd');
    this.searchTime = [toDay, nextDay];
    this.projectId = this.cache.currentProject.projectId;
    this.washTotal = [{ name: '总数', value: 0 }, { name: '已清扫', value: 0 }, { name: '需清扫', value: 0 }];

  }

  ngOnInit() {
  }

  ionViewWillEnter() {
    this.init();
  }

  ionViewWillLeave() {
  }

  init() {
    this.dataService.getWashRoom(this.projectId).subscribe(res => {
      console.log(res.data.datas);
      const Ids = [];
      for (const item of res.data.datas) {
        Ids.push(item.areaId);
      }
      this.dataService.getWashRoomParams(Ids).subscribe(items => {
        console.log(items)
        // 获取对应设备的设备id及设备参数id
        console.log(res.data.datas, items.data)

        for (const item of res.data.datas) {
          item.deviceParams = [];
          if (items && items.data.length) {
            for (const ite of items.data) {
              if (ite.areaId === item.areaId && ite.deviceParameterCode === 2006) {
                item.deviceParams.push({ deviceId: ite.deviceId, deviceParameterId: ite.deviceParameterCode });
              }
            }
          }
        }

        // 将告警放入对应的洗手间
        this.getWashAlarmList().subscribe(data => {
          console.log(res.data.datas)
          const areaIds = [];
          for (const item of res.data.datas) {
            areaIds.push(item.areaId)
            console.log(item.areaName.length)
            if (item.areaName.length > 8) {
              item.areaName = item.areaName.substr(0, 8) + '...';
            }
            Ids.push(item.areaId);
            item.alarms = [];
            item.arrive = [];
            item.arrived = [];
            item.deviceId = item && item.deviceParams[0] && item.deviceParams[0].deviceId ? item.deviceParams[0].deviceId : null;
            item.deviceparameterId = item && item.deviceParams[0] && item.deviceParams[0].deviceparameterId ? item.deviceParams[0].deviceparameterId : null;
            if (data) {
              for (const dat of data) {
                if (dat.deviceId === item.deviceId && !dat.confirmTime && !dat.presentTime) {
                  console.log(dat)
                  item.alarms.push(dat);
                }
                if (dat.deviceId === item.deviceId) {
                  if (dat.presentTime) {
                    item.arrived.push(dat);
                  }
                }
              }
            }
            item.arrive = this.arrayUnique(item.arrived, 'presentTime');
            console.log('到场数据', item.arrive)
            // 到场次数
            item.arrived = item.arrive.length;
          }
          this.dataService.getWashFeedback(areaIds).subscribe(over => {
            if (over.data && over.data.areaQuesInfos && over.data.areaQuesInfos.length) {
              for (const item of res.data.datas) {
                for (const overTime of over.data.areaQuesInfos) {
                  if (overTime.areaId === item.areaId) {
                    item.isOverTime = overTime.isOverTime;
                  }
                }
              }
            }
            this.washRoom = this.dealResult(this.getRoomGroup(res.data.datas));
            console.log('洗手间数据', this.washRoom);
            this.getNumber(res.data.datas);
          });
        });

      })
    })
  }

  // 计算汇总数据
  getNumber(data) {
    let cleanNum = 0;
    for (const dat of data) {
      if (dat.alarms.length) {
        cleanNum += 1;
      }
    }
    this.washTotal[0].value = data.length;
    this.washTotal[2].value = cleanNum;
    this.washTotal[1].value = this.washTotal[0].value - this.washTotal[2].value;
  }

  // 将数据分为4*n组
  getRoomGroup(data) {
    const result = [];
    for (let i = 0; i < data.length; i += 4) {
      result.push(data.slice(i, i + 4));
    }
    return result;
  }

  arrayUnique(arr, name) {
    const hash = {};
    return arr.reduce(function (item, next) {
      hash[next[name]] ? '' : hash[next[name]] = true && item.push(next);
      return item;
    }, []);
  }

  // 处理数据内容显示
  dealResult(result) {
    // 设置弹框显示内容
    if (result) {
      for (const data of result) {
        data.itemShown = false;
        for (const item of data) {
          item.Active = false;
          data.deviceName = item.deviceName;
          data.deviceStatus = item.deviceStatus;
          data.cleanNum = item.arrived;
        }
      }
      // 判断是否默认显示
      // if (result.length <= 2) {
      for (let i = 0; i < result.length; i++) {
        this.lastItem = result[0][0];
        result[0].itemShown = true;
        result[0][0].Active = true;
        result[0].cleanNum = result[0][0].arrived;
      }
      this.xItem = this.yItem = 0;
      const deviceParameterId = [];
      if (result[0] && result[0][0]) {
        this.getfeedBack(result[0][0], result[0]);
        if (result[0][0].deviceParams[0]) {
          deviceParameterId.push(result[0][0].deviceParams[0].deviceparameterId);
          this.getHistoryData(this.projectId, 24, result[0][0], result[0]);
        }
      }
      // }
    }
    return result;
  }

  // 获取洗手间告警列表
  getWashAlarmList(): Observable<any> {
    return new Observable(responseObserver => {
      const startTime = this.datePipe.transform(new Date(), 'yyyy-MM-dd 00:00:00');
      const endTime = this.datePipe.transform(new Date(), 'yyyy-MM-dd 23:59:59');
      this.dataService.getWashAlarm(this.projectId, startTime, endTime).subscribe(res => {
        for (const data of res.data.datas) {
          if (data.presentTime) {
            data.presentTime = data.presentTime.substr(0, data.presentTime.length - 3);
            data.presentTime = this.datePipe.transform(new Date(data.presentTime), 'yyyy-MM-dd HH:mm:ss');
          }
        }
        responseObserver.next(res.data.datas);
        responseObserver.complete();
      })
    })
  }

  choose(index1, index2, item, data) {
    console.log(item)
    if (this.lastItem && item.areaId === this.lastItem.areaId) {
      console.log(this.lastItem);
      item.Active = !item.Active;
    } else {
      if (this.lastItem) {
        this.lastItem.Active = false;
      }
      item.Active = true;
    }
    if (this.xItem === index1 && this.yItem === index2) {
      data.itemShown = !data.itemShown;
    } else {
      if (this.lastData) {
        if (this.lastData === data) {
          this.lastData.itemShown = true;
        } else {
          data.itemShown = true;
          this.lastData.itemShown = false;
        }
      } else {
        data.itemShown = true;
      }
      this.xItem = index1;
      this.yItem = index2;
      data.deviceName = item.deviceName;
      data.deviceStatus = item.deviceStatus;
      data.cleanNum = item.arrived;
    }
    this.lastItem = item;
    this.lastData = data;

    // 刷新反馈统计
    this.getfeedBack(item, data);

    // 刷新历史曲线
    this.getHistoryData(this.projectId, 24, item, data)
  }

  // 获取洗手间设备间问题反馈统计
  getfeedBack(item, data) {
    if (item) {
      this.dataService.getWashFeedback([item.areaId]).subscribe(res => {
        console.log(res)
        data.feedBackCount = 0;
        data.feedBack = [];
        console.log(res.data.areaQuesInfos)
        if (res.data && res.data.areaQuesInfos && res.data.areaQuesInfos.length) {
          if (res.data.areaQuesInfos[0].quesItems && res.data.areaQuesInfos[0].quesItems.length) {
            for (const ite of res.data.areaQuesInfos[0].quesItems) {
              ite.percent = ite.quesDataCount + '%';
            }
          }
          data.feedBackCount = res.data.areaQuesInfos[0].total || 0;
          data.feedBack = res.data.areaQuesInfos[0].quesItems ? res.data.areaQuesInfos[0].quesItems.sort(this.sortCompare('quesDataCount')) : [];
        }
      });
    }
  }

  // 获取洗手间历史曲线
  getHistoryData(projectId, displayCount, item, data) {
    const date = new Date();
    const toDay = this.formatDate(date, 'yyyy-MM-dd');
    const nextday = + date + 1000 * 60 * 60 * 24;
    const nextDay = this.formatDate(new Date(nextday), 'yyyy-MM-dd');
    const searchTime = [toDay, nextDay]
    const deviceId = item && item.deviceParams[0] && item.deviceParams[0].deviceId ? item.deviceParams[0].deviceId : null;
    const deviceParameterId = [2006];
    this.dataService.getDeviceParamesHistoryData(projectId, deviceId, deviceParameterId, displayCount, searchTime).subscribe(res => {
      let minNum = 0;
      let maxNum = 0;
      if (res.data && res.data.length > 0) {
        for (let index = 0; index < res.data.length; index++) {
          const element = res.data[index];
          const points = element.point;
          const arrMax = [];
          if (points) {
            minNum = points[0].y;
            for (const data of points) {
              arrMax.push(data.y)
            }
          }
          console.log(arrMax)
          maxNum = Math.max.apply(null, arrMax)
          console.log(maxNum, minNum)
          if (maxNum === minNum) {
            data.totalNum = maxNum;
          } else {
            data.totalNum = (maxNum - minNum) || 0;
          }
          const chartdata = this.formatResponse(res, item);
          console.log(chartdata)
          this.options = this.washCharts.showLine(chartdata, item);
          console.log(this.options)
        }
      }
    });
  }


  /**
   * 历史数据格式化
   * @param res
   */
  formatResponse(res, items) {
    const ret = [];
    const data = res.data;
    if (data && data.length > 0) {
      for (let index = 0; index < data.length; index++) {
        const element = data[index];
        const temp = {
          xdata: [],
          ydata: []
        };
        const points = element.point;
        points.sort(this.getSortFun('asc', 'x'));

        if (points) {
          for (let i = 0; i < points.length; i++) {
            const point = points[i];
            point.x = this.datePipe.transform(new Date(point.x), 'yyyy-MM-dd HH:mm:ss');
            temp.xdata.push(point.x);
            if (point.y !== null && points[0].y !== null) {
              temp.ydata.push(point.y - points[0].y);
            } else if (point.y !== null && points[0].y === null) {
              temp.ydata.push(point.y - points[0].y);
            } else {
              temp.ydata.push(null);
            }
          }
          temp.xdata = this.sortKey(temp.xdata);
        }
        ret.push(temp);
      }
    }
    return ret;
  }

  getSortFun(order, sortBy) {
    const ordAlpah = (order === 'asc') ? '>' : '<';
    const sortFun = new Function('a', 'b', 'return a.' + sortBy + ordAlpah + 'b.' + sortBy + '?1:-1');
    return sortFun;
  }

  sortKey(array) {
    for (let i = 0; i < array.length; i++) {
      array[i] = (new Date(array[i])).getTime()
    }
    array.sort(function (a, b) {
      return a > b ? 1 : -1;
    });
    return array;
  }

  sortCompare(property) {
    return (a, b) => {
      const value1 = a[property];
      const value2 = b[property];
      return value2 - value1;
    }
  }

  formatDate(date, fmt) {
    const o = {
      'M+': date.getMonth() + 1,                   // 月份
      'd+': date.getDate(),                        // 日
      'h+': date.getHours(),                       // 小时
      'm+': date.getMinutes(),                     // 分
      's+': date.getSeconds(),                     // 秒
      'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
      'S': date.getMilliseconds()                  // 毫秒
    };
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (const k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
      }
    }
    return fmt;
  }

}
